package de.baumann.browser.fragments

import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import de.baumann.browser.R
import de.baumann.browser.adapter.NewsItemAdapter
import de.baumann.browser.api.net.vo.NewsItem
import de.baumann.browser.base.BaseOdinFragment
import de.baumann.browser.iview.INewsView
import de.baumann.browser.present.NewsListPresenter
import kotlinx.android.synthetic.main.fragment_news_list.*
import java.util.*


class NewsListFragment : BaseOdinFragment<INewsView, NewsListPresenter>(), INewsView {
    private var mNewsAdapter: NewsItemAdapter? = null
    private var isAllowLoadMore = false

    override fun getLayout(): Int {
        return R.layout.fragment_news_list
    }

    override fun initView(view: View) {
        refreshNews.setColorSchemeColors(
                resources.getColor(android.R.color.holo_red_light),
                resources.getColor(android.R.color.holo_green_light),
                resources.getColor(android.R.color.holo_blue_light))
        refreshNews!!.setOnRefreshListener { getPresenter()!!.refresh() }
        rvNewsList.setHasFixedSize(false)
        rvNewsList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (isSlideToBottom(rvNewsList) && isAllowLoadMore) {
                    getPresenter().loadMore()
                }
            }
        })
        val layoutManager = LinearLayoutManager(context!!.applicationContext)
        rvNewsList.layoutManager = layoutManager
        mNewsAdapter = NewsItemAdapter(context)
        rvNewsList.adapter = mNewsAdapter
    }

    override fun initData() {
        assert(arguments != null)
        getPresenter().loadNormal()
    }

    override fun getColumnId(): String? {
        return arguments!!.getString("columnId")
    }

    override fun refreshNewsList(newsSummaries: List<NewsItem>, isRefresh: Boolean) {
        isAllowLoadMore = newsSummaries.size >= 50
        if (isRefresh) {
            refreshNews!!.isRefreshing = false
            mNewsAdapter!!.setNewsList(newsSummaries as ArrayList<NewsItem>)
        } else {
            mNewsAdapter!!.addNewsList(newsSummaries as ArrayList<NewsItem>)
        }
    }

    override fun createPresenter(): NewsListPresenter? {
        return NewsListPresenter()
    }

    override fun createView(): INewsView? {
        return this
    }

    companion object {


        fun isSlideToBottom(recyclerView: RecyclerView?): Boolean {
            if (recyclerView == null) {
                return false
            }
            return recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange()
        }
    }

    override fun showBindEth(): Boolean {
        return false
    }
}
